package com.glory.brepda.activity.mfg;

import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.LotBatchListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotList;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class WorkBatchEndActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvEqpWorkID)
    TextView tvEqpWorkID;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llEQPLayout)
    LinearLayout llEQPLayout;
    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.etPSM)
    FreeUI_ClearEditText etPSM;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.eqpScan)
    ImageView eqpScan;
    @BindView(R.id.psmScan)
    ImageView psmScan;
    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private static final int REQUEST_CODE_TEXT3 = 1003;
    private LotBatchListAdapter mAdapter;
    private String mEquipmentid = "";
    private int mCount = 0;
    private LotInfoEntity lotInfoEntity;
    private String subqty = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_batch_begin;
    }

    @Override
    protected void initView() {
//        tvEqpWorkID.setVisibility(View.VISIBLE);
        llEQPLayout.setVisibility(View.GONE);
        tvBaseSubmit.setVisibility(View.GONE);
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvCount.setText("计数:" + mCount);
        etLot.requestFocus();
        initRecyclerView(rvLotList, this);
        mAdapter = new LotBatchListAdapter(null, false, () -> tvCount.setText("计数:" + --mCount));
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        rvLotList.setAdapter(mAdapter);
        initEdit(etEqpWorkID, s -> {
            if (s.equals("Submit")) {
                Submit();
                etEqpWorkID.setText("");
                etEqpWorkID.requestFocus();
                return;
            }
            etLot.requestFocus();
        });
        initEdit(etLot, s -> {
            if (s.equals("Submit")) {
                Submit();
                etLot.setText("");
                etLot.requestFocus();
                return;
            }
            new Handler().postDelayed(() -> etLot.requestFocus(), 500);
            if (containLot(s, mAdapter.getData())) {
                showToast("当前批次已在列表中", false);
                return;
            }
            LotUtils.searchLotInfo(WorkBatchEndActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {

                    if (!response.getLOT().getSTATE().equals("正在作业")) {
                        etLot.setText("");
                        etLot.requestFocus();
                        showToast("批次状态不允许", false);
                        return;
                    }

                    if (response.getLOT().getHOLDSTATE().equals("On")) {
                        etLot.setText("");
                        etLot.requestFocus();
                        showToast("批次状态不允许", false);
                        return;
                    }
                    mEquipmentid = response.getLOT().getEQUIPMENTID();
                    lotInfoEntity = response;
                    subqty = lotInfoEntity.getLOT().getSUBQTY();
                    submit(s,String.valueOf(response.getLOT().getMAINQTY()));

                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });
    }

    private void Submit() {
        if (mAdapter.getData().size() <= 0) {
            showToast("请先添加批次信息", false);
            return;
        }
        LotUtils.lotDAWBTrackOut(this, "BATCHLOTTRACKOUT", getSupportFragmentManager(), "", getText(etEqpWorkID),
                getText(etLot), null, null, "", subqty, lotInfoEntity, 0,
                "0", null,new LotUtils.netCallback() {
                    @Override
                    public void onSuccess(Object response) {

                    }

                    @Override
                    public void onFail(Throwable t) {

                    }
                });
    }

    private boolean containLot(String s, List<LotInfoEntity.LotBean> data) {
        if (data.size() <= 0)
            return false;
        for (LotInfoEntity.LotBean entity : data) {
            if (entity.getLOTID().equals(s))
                return true;
        }
        return false;
    }

    @Override
    protected void initData() {

        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        eqpScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });
        psmScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT3);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etEqpWorkID.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT3:
                        etPSM.setText(qrResult);
                        break;
                }
            }

        }
    }



    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
        Submit();
    }

    private void submit(String lotID, String mainQTY) {
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), WorkBatchEndActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showToast("出站成功", true);
                    mAdapter.addData(response.body().getResponse().getBody().getLOTLIST());
                    tvCount.setText("计数:" + mAdapter.getData().size());
                }
                etLot.setText("");
                etLot.requestFocus();
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "TRACKOUT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "DefaultTrackOut");
        map.addProperty("EQUIPMENTID", mEquipmentid);
        map.addProperty("ISCHECKSTEPAUTHORITY", false);
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID, mainQTY));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
        NetUtils.requestPostNet("IF.LOTTRACKOUT", "BATCHLOTTRACKOUT", WorkBatchEndActivity.this, map, callBack);
//        NetUtils.requestMESPostNet("CPC.LOTTRACKOUT",WorkBatchEndActivity.this,map,callBack);
    }
}